import {
  format,
  subDays,
  isToday,
  isYesterday,
  isWithinInterval,
} from "date-fns";
import type { ChatHistoryList, CategorizedChats } from "@/types";

export const chatNowTime = (
  categorizedChats: CategorizedChats[]
): CategorizedChats[] => {
  const nowTime = new Date();

  const resultMap = new Map<string, ChatHistoryList[]>();

  const categoryRules = [
    { name: "今天", condition: (date: Date) => isToday(date) },
    { name: "昨天", condition: (date: Date) => isYesterday(date) },
    {
      name: "最近3天",
      condition: (date: Date) =>
        isWithinInterval(date, {
          start: subDays(nowTime, 3),
          end: subDays(nowTime, 1),
        }),
    },
    {
      name: "最近7天",
      condition: (date: Date) =>
        isWithinInterval(date, {
          start: subDays(nowTime, 7),
          end: subDays(nowTime, 3),
        }),
    },
    {
      name: "最近30天",
      condition: (date: Date) =>
        isWithinInterval(date, {
          start: subDays(nowTime, 30),
          end: subDays(nowTime, 7),
        }),
    },
  ];

  // 展开所有 thisChats 并分类
  const allChats = categorizedChats.flatMap((cat) => cat.thisChats);

  for (const chat of allChats) {
    const chatDate = new Date(chat.createdAt);
    let categoryName: string | undefined;

    for (const rule of categoryRules) {
      if (rule.condition(chatDate)) {
        categoryName = rule.name;
        break;
      }
    }

    if (!categoryName) {
      categoryName = format(chatDate, "yyyy-MM");
    }

    if (!resultMap.has(categoryName)) {
      resultMap.set(categoryName, []);
    }

    resultMap.get(categoryName)!.push(chat);
  }

  // 转换为数组并按时间降序排
  const result: CategorizedChats[] = Array.from(resultMap.entries()).map(
    ([timeName, thisChats]) => ({
      timeName,
      thisChats: thisChats.sort(
        (a, b) =>
          new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      ),
    })
  );

  // 可选：按每组第一个聊天的时间降序排序
  result.sort((a, b) => {
    const dateA = a.thisChats[0]?.createdAt || "";
    const dateB = b.thisChats[0]?.createdAt || "";
    return new Date(dateB).getTime() - new Date(dateA).getTime();
  });

  return result;
};
